import 'package:flutter/material.dart';
import 'package:hong_vpn_new_20240626/ui/chat/chat_cell.dart';
import 'package:hong_vpn_new_20240626/utils/Configs/ai_config.dart';
import 'package:hong_vpn_new_20240626/utils/global.dart';
import 'package:hong_vpn_new_20240626/utils/models/ai_model.dart';

import '../../utils/api.dart';
import '../../utils/models/chat.dart';
import '../../utils/utils.dart';
import 'chat_textfield.dart';

class ChatWidget extends StatefulWidget {
  final AiModel? model;

  const ChatWidget({super.key, required this.model});

  @override
  State<ChatWidget> createState() => _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
  late ScrollController _scrollController;

  late TextEditingController _textController;

  static List<ChatModel> chats = [];

  final ChatModel _loading =
      ChatModel(role: UserRole.loading, content: "Loading...");

  @override
  void initState() {
    super.initState();
    AiConfig.addChat(widget.model);

    _textController = TextEditingController();

    _scrollController = ScrollController();

    if (chats.isEmpty) {
      var welcom =
          ChatModel(role: UserRole.welcome, content: "Hi, Can i help you?");
      chats.insert(0, welcom);
      setState(() {});
    }
  }

  bool _canSendTap(String text) {
    if (text.isEmpty) {
      // 空的不能发送
      return false;
    }
    if (chats.contains(_loading)) {
      // 正在加载中的不能发送
      return false;
    }
    _sendTap(text);
    return true;
  }

  _sendTap(String text) async {
    var question = ChatModel(
        content: text, role: UserRole.user, time: Utils.getCurrentTime());
    chats.insert(0, question);
    chats.removeWhere((element) => element == _loading);
    chats.insert(0, _loading);
    setState(() {});
    _scrollController.animateTo(0,
        duration: const Duration(milliseconds: 250), curve: Curves.bounceInOut);

    var data = chats
        .where((element) {
          var isConfigModel = element.role == UserRole.assistant ||
              element.role == UserRole.user;
          return isConfigModel;
        })
        .toList()
        .reversed
        .toList();

    try {
      var result = await API.chat(data);
      chats.insert(0, result);
    } catch (e) {
      var result = ChatModel(
          role: UserRole.error,
          content: e.toString(),
          time: Utils.getCurrentTime());
      chats.insert(0, result);
    }
    chats.removeWhere((element) => element == _loading);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Chat"),
        elevation: 0.5,
        shadowColor: Colors.white,
        scrolledUnderElevation: 0.5,
        actions: [
          IconButton(
              onPressed: () {},
              icon: Container(
                width: 36,
                height: 36,
                clipBehavior: Clip.hardEdge,
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(18)),
                child: Image.asset(
                  widget.model?.header ?? "assets/images/Rectangle 49.png",
                  fit: BoxFit.cover,
                ),
              ))
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              physics: const AlwaysScrollableScrollPhysics(),
              controller: _scrollController,
              padding: EdgeInsets.zero,
              itemCount: chats.length,
              reverse: true,
              itemBuilder: (BuildContext context, int index) {
                return ChatCellWidget(chatModel: chats[index]);
              },
            ),
          ),
          ChatTextFieldWidget(
            textEditingController: _textController,
            beginEditTap: () {
              _scrollController.animateTo(0,
                  duration: const Duration(milliseconds: 250),
                  curve: Curves.bounceInOut);
            },
            sendTap: (text) => _canSendTap(text),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _textController.dispose();
    super.dispose();
  }
}
